<template>
  <div class="container">
    <video
      src="https://halberd-1.oss-cn-beijing.aliyuncs.com/179ea1ca1823030dd1d1d057708bf0e5.mp4"
      class="background-video"
      muted
      loop
      autoplay
    ></video>

    <div class="login_form" :style="styleWidth">
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <h1 class="title" v-text="title"></h1>
        <!-- 二维码角标 -->
        <i :class="['iconfont', 'jiaobiao', jiaobiaoType]" @click="change"></i>

        <!-- 常规登录 -->
        <common
          @syncRuler="handleSyncRuler"
          @submit="handleSubmit"
          ref="commonLogin"
          v-if="this.loginType === 'common'"
          @changeLogin="handlechangeLogin"
        ></common>

        <!-- 短信验证登录 -->
        <message
          :storageUserInfo="storageUserInfo"
          v-else-if="this.loginType === 'sendMessage'"
        ></message>

        <!-- 二维码 -->
        <scanCode :storageUserInfo="storageUserInfo" v-else></scanCode>
      </el-form>
    </div>
  </div>
</template>

<script>
import * as api from "@/api/users";
import storage from "@/utils/storage";
import common from "@/components/login/commonLogin.vue";
import message from "@/components/login/msgLogin.vue";
import scanCode from "@/components/login/qrLogin.vue";

// 校验验证码
var checkCaptcha = (rule, value, callback) => {
  var captcha = /^[A-Za-z0-9]{5}$/;
  if (captcha.test(value)) {
    callback();
  } else {
    callback("验证码错误");
  }
};
// 校验用户名
var validateUsername = (rule, value, callback) => {
  // console.log(rule);
  // console.log(value);
  //用户名正则，3到16位（字母，数字，下划线，减号）
  var uPattern = /^[a-zA-Z0-9_-]{3,16}$/;
  //判断
  if (uPattern.test(value)) {
    callback();
  } else {
    callback("3到16位（字母，数字，下划线，减号）");
  }
};
// 校验密码
var validatePassword = (rule, value, callback) => {
  //密码3到16位字母或者数字
  var uPassword = /^[0-9a-zA-Z]{3,16}$/;
  if (uPassword.test(value)) {
    callback();
  } else {
    callback("至少3到16位字母或者数字");
  }
};
export default {
  components: {
    common,
    message,
    scanCode,
  },
  data() {
    return {
      // 登录输入框的数据
      ruleForm: {
        username: "",
        password: "",
        captcha: "",
      },
      //页面   common常规页面   qrCode二维码页面    sendMessage短息验证页面
      loginType: "common",
      title: "管理系统",
      styleWidth: {
        height: "550px",
      },
      // 表单验证规则
      rules: {
        username: [{ validator: validateUsername, trigger: "blur" }],
        password: [{ validator: validatePassword, trigger: "blur" }],
        captcha: [{ validator: checkCaptcha, trigger: "blur" }],
      },
    };
  },
  computed: {
    jiaobiaoType() {
      if (this.loginType === "common") {
        return "icon-erweimajiaobiao";
      }
      if (this.loginType === "qrCode" || this.loginType === "sendMessage") {
        return "icon-diannaojiaobiao";
      }
    },
  },
  methods: {
    // 表单验证
    handleSyncRuler(input) {
      // console.log(input);
      this.ruleForm = input;
    },

    // 表单提交验证
    // ref作用在子组件上，可以获取子组件的实例
    //ref用于给子组件或dom注册引用信息  父组件可以通过$refs拿到子组件引用信息（子传父）
    handleSubmit() {
      // console.log(this.$refs);
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          // 本地校验通过
          // alert("submit!");
          // 登入
          // 1.获取后台的验证码
          // 2.进行本地校验
          // 3.本地校验通过   =>   先校验验证码
          // 4.验证码通过再校验用户名和密码
          // 5.成功 和 失败
          api.verifyCaptcha(this.ruleForm.captcha).then((res) => {
            // console.log(res);
            // 判断验证是否通过
            if (res.data.state) {
              // 通过就校验用户名和密码
              let { username, password } = this.ruleForm;
              api.loginApi(username, password).then((res) => {
                // console.log(res, 1234);
                // 判断登入是否成功
                if (res.data.state) {
                  // 登录成功
                  // 1.存储用户信息到本地
                  this.storageUserInfo(res.data);
                  // 2.跳转到主页
                  this.$router.push("/welcome");
                }
              });
            } else {
              //如果不通过就刷新验证码
              this.$refs["commonLogin"].getCaptchas();
            }
          });
        } else {
          // 本地校验不通过
          console.log("error submit!!");
          return false;
        }
      });
    },
    //封装一个存储用户信息 token permission的方法
    storageUserInfo({ userInfo, token, permission }) {
      //将用户信息存储到vuex
      this.$store.commit("users/SET_USERINFO", userInfo);
      storage.set("userInfo", userInfo);
      storage.set("token", token);
      storage.set("permission", permission);
      console.log(userInfo, 5);
    },
    //切换扫码页面
    change() {
      if (this.loginType === "common") {
        this.loginType = "qrCode";
        this.title = "微信扫码登录";
        this.styleWidth.height = "480px";
      } else if (
        this.loginType === "qrCode" ||
        this.loginType === "sendMessage"
      ) {
        this.loginType = "common";
        this.title = "管理系统";
        this.styleWidth.height = "550px";
      }
    },
    // 切换短信页面
    handlechangeLogin() {
      this.loginType = "sendMessage";
      this.title = "短信验证码登录";
      this.styleWidth.height = "480px";

      console.log(11);
    },
  },
};
</script>

<style lang="less" scoped>
// 修改element-ui的样式
// 1.打开调试器，找准类名，覆盖样式
// 2.看权重，使用！important
// 使用深度选择器 >>> /deep/ vue::deep

.background-video {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  object-fit: cover;
  width: 100%;
  height: 100%;
}
.login_form {
  position: fixed;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  margin: auto;
  width: 420px;
  height: 550px;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 5px;
  user-select: none;
}

.title {
  margin: 68px 0 54px 0;
  text-align: center;
  color: white;
}
.jiaobiao {
  position: absolute;
  right: 1px;
  top: -2px;
  font-size: 60px !important;
  color: #fff;
  cursor: pointer;
}
</style>
